import { EnumChapterStatus, ErrorCode } from "@/models/constant";
import { delChapterUsingPost, listMyNovelChapterUsingGet } from "@/services/novel-web/chapterController";
import { MessageError, ToLogin } from "@/utils/commonUtils";
import { DeleteOutlined, EditOutlined, ExclamationCircleFilled } from "@ant-design/icons";
import { history } from "@umijs/max";
import { Button, Divider, message, Modal, Row, Space, Table } from "antd";
import { ColumnsType } from "antd/es/table";
import moment from 'moment';
import { useEffect, useState } from "react";
import styles from './ChapterManage.less';



interface ChapterManageProps {
  novelId: number;
}

const ChapterManage : React.FC<ChapterManageProps> = ({novelId})=>{

  const [data,setData] = useState<API.Chapter[]>([]);
  const loadData = async () =>{
    try {
      const resp = await listMyNovelChapterUsingGet({
        novelId: novelId,
      })
      
      setData(resp.data ?? [])
      
    } catch (error: any) {
      MessageError(error);
      if(error.info.code == ErrorCode.NOT_LOGIN_401) {
        ToLogin();
      }
    }
  };
  useEffect(()=>{
    loadData();
  },[]);

  const handleToNew = ()=>{
    history.push(`/writer/new-chapter/${novelId}`);
  };

  // handle actions

  const handleEditAction = (record: API.Chapter) =>{
    history.push(`/writer/modify-chapter/${novelId}/${record.id}`);
  };

  const handleDelAction = (record: API.Chapter) =>{
    Modal.confirm({
      title: '确定删除该章节内容？',
      icon: <ExclamationCircleFilled />,
      content: '删除该章节内容后无法撤回',
      onCancel() {},
      onOk() {
        toDelChapter(record);
      },
      
    });
  };

  const toDelChapter = async (record: API.Chapter)=>{
    try {
      const resp = await delChapterUsingPost({
        chapterId: record.id ?? -1,
      });
      if(resp) {
        setData(data.filter(one => one.id != record.id));
        message.success("删除成功");
      }
    } catch (error) {
      MessageError(error);
    }
  };

 

  const columns: ColumnsType<API.Chapter> =[
    {
      title: 'id',
      dataIndex: 'id',
      hidden: true,
    },
    {
      title: '章节名称',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value, record, index) => EnumChapterStatus.getDescFromValue(value)
      
    },
    {
      title: '创建时间',
      dataIndex: 'updateTime',
      render: (val) =>(
        moment(val).format('YYYY-MM-DD HH:mm')
      ),
    },
    {
      title: '操作',
      render: (_,record)=>(
        <Space size={'middle'}>
          <a onClick={()=>handleEditAction(record)}>
            <EditOutlined className={styles.clickEnable}/>
          </a>
          <a onClick={()=>handleDelAction(record)}>
            <DeleteOutlined className={styles.clickEnable}/>
          </a>
        </Space>
      ),
    }
  ];

  return (
    <>
      <Row align={"middle"} justify={"space-between"} style={{ margin: 8 }}>
        <div style={{ fontWeight: "bolder", fontSize: 16 }}>
          {"章节管理"}
        </div>
        <Button type="primary" onClick={()=>handleToNew()}>
            {"新建章节"}
        </Button>
      </Row>
      <Divider/>
      <Table<API.Chapter>
        dataSource={data}
        columns={columns}
        size={"middle"}
        pagination={false}
        // pagination={{position:['none','bottomCenter']}}

      /> 
    </>
  );
};

export default ChapterManage;
